package org.example.apply.controller;


import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bw.activity7.activiti.pojo.ActivitiVo;
import com.bw.activity7.activiti.pojo.UserTask;
import com.bw.activity7.activiti.pojo.Variable;
import com.bw.activity7.activiti.service.ActivitiService;
import com.bw.itext.pdf.service.PdfService;
import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.runtime.ProcessInstance;
import org.example.apply.entity.Apply;
import org.example.apply.entity.UserDto;
import org.example.apply.feign.MsgFeign;
import org.example.apply.service.IApplyService;
import org.example.apply.utils.MyJwtUtil;
import org.example.apply.utils.ResultJson;
import org.example.apply.utils.WebUtils;
import org.joda.time.format.DateTimeFormat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author lyk
 * @since 2022-10-11
 */
@Slf4j
@RestController
@RequestMapping("/apply")
public class ApplyController {

    @Autowired
    IApplyService applyService;

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    ActivitiService activitiService;

    @Autowired
    RuntimeService runtimeService;

    @Autowired
    KafkaTemplate kafkaTemplate;


    @Autowired
    PdfService pdfService;

    /**
     * 流程发布
     * @return
     */
    @GetMapping("/deploy")
    public ResultJson deploy() {
        activitiService.createDeployment("合同流程部署","hetong","bpmn/hetong-1.bpmn");
        return ResultJson.success("部署成功");
    }


    /**
     * pdf导出
     * @throws IOException
     */
    @RequestMapping("/export")
    public void export() throws IOException {
        List<Apply> list = applyService.list();
        pdfService.export(list,"month.pdf", "合同单",Apply.class);
        pdfService.sign("month.pdf","newmonth.pdf");
        pdfService.preview("newmonth.pdf",WebUtils.getResponse());
    }

    /**
     *
     * @param id
     * @return
     */
    @GetMapping("/biz")
    public ResultJson biz(Integer id) {
        //当前用户
        String token = WebUtils.getRequest().getHeader("token");
        UserDto userDto = MyJwtUtil.pareseToken(token, UserDto.class);
        //合同信息
        QueryWrapper<Apply> wrapper = new QueryWrapper<>();
        wrapper.eq("id", id);
        Apply apply = applyService.getOne(wrapper);
        //启动工作流
        ActivitiVo activitiVo = new ActivitiVo();
        activitiVo.setDeploymentKey("hetong");
        activitiVo.setUsername(userDto.getUsername());
        activitiVo.setBusinessKey(id+"");
        List<Variable> varList = new ArrayList<>();
        varList.add(new Variable("zhangsan", "zhangsan"));
        varList.add(new Variable("lisi", "lisi"));
        varList.add(new Variable("wangwu", "wangwu"));
        varList.add(new Variable("money", apply.getMoney()+""));
        activitiVo.setVariables(varList);
        ProcessInstance processInstance = activitiService.askForBiz(activitiVo);
        //更新流程Id
        UpdateWrapper<Apply> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id",id);
        updateWrapper.set("status",1);
        updateWrapper.set("taskid",processInstance.getProcessInstanceId());
        applyService.update(updateWrapper);
        //MQ异步通知，相关人合同审核
        kafkaTemplate.send("month1011", UUID.randomUUID().toString(),JSONUtil.toJsonStr(apply));
        log.info("合同审核，邮件通知：" + apply.getTitle());
        return ResultJson.success(processInstance.toString());
    }

    /**
     * 我的代办
     * @return
     */
    @GetMapping("/query")
    public ResultJson query() {
        String token = WebUtils.getRequest().getHeader("token");
        UserDto userDto = MyJwtUtil.pareseToken(token, UserDto.class);
        ActivitiVo vo = new ActivitiVo();
        vo.setUsername(userDto.getUsername());
        List<UserTask> userTasks = activitiService.queryUserTaskByUserName(vo);
        SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
        List<Map<String, Object>> myTaskList = new ArrayList<>();
        for (UserTask userTask : userTasks) {
            String businessKey = userTask.getHistoricProcessInstance().getBusinessKey();
            Apply apply = applyService.getById(businessKey);
            Map<String, Object> myTask = new HashMap<>();
            myTask.put("userTask", userTask);
            myTask.put("apply", apply);
            Date startTime = userTask.getHistoricProcessInstance().getStartTime();
            myTask.put("time", formatter.format(startTime));
            myTaskList.add(myTask);
        }
        return ResultJson.success(myTaskList);
    }

    /**
     * 审核功能
     * @param activitiVo
     * @return
     */
    @PostMapping("/complete")
    public ResultJson complete(@RequestBody ActivitiVo activitiVo) {
        System.err.println(activitiVo);
        String token = WebUtils.getRequest().getHeader("token");
        UserDto userDto = MyJwtUtil.pareseToken(token, UserDto.class);
        activitiVo.setUsername(userDto.getUsername());
        activitiService.completeUserTaskById(activitiVo);

        UpdateWrapper<Apply> wrapper1 = new UpdateWrapper<>();
        if (activitiVo.isAuditFlag() == true && activitiVo.getUsername().equals("wangwu")) {
            wrapper1.eq("taskid",activitiVo.getProcessInstanceId());
            wrapper1.set("status",2);
            applyService.update(wrapper1);
        }else{
            wrapper1.eq("taskid",activitiVo.getProcessInstanceId());
            wrapper1.set("status",3);
            applyService.update(wrapper1);
        }
        QueryWrapper<Apply> applyQueryWrapper = new QueryWrapper<>();
        applyQueryWrapper.eq("taskid", activitiVo.getProcessInstanceId());
        Apply apply = applyService.getOne(applyQueryWrapper);
        System.err.println(apply);

        return ResultJson.success("审核成功");
    }

    /**
     * 合同管理
     * @param page
     * @param size
     * @param apply
     * @return
     */
    @GetMapping("/list")
    public Page<Apply> list(@RequestParam(defaultValue = "1")int page,@RequestParam(defaultValue = "3")int size,Apply apply) {
        System.err.println(apply);
        Page<Apply> applyPage = new Page<>(page, size);
        QueryWrapper<Apply> wrapper = new QueryWrapper<>();


        String token = WebUtils.getRequest().getHeader("token");
        UserDto userDto = MyJwtUtil.pareseToken(token, UserDto.class);
        wrapper.eq("user_id", userDto.getId());

        if (!StringUtils.isEmpty(apply.getTitle())) {
            wrapper.like("title",apply.getTitle());
        }
         if (!StringUtils.isEmpty(apply.getReason())) {
             wrapper.like("reason",apply.getReason());
        }
         if (!StringUtils.isEmpty(apply.getRemark())) {
             wrapper.like("remark",apply.getRemark());
        }

        wrapper.orderByDesc("id");

        Page<Apply> page1 = applyService.page(applyPage, wrapper);
        return page1;
    }


    @PostMapping("/save")
    public ResultJson save(@RequestBody Apply apply) {
        String token = WebUtils.getRequest().getHeader("token");
        UserDto userDto = MyJwtUtil.pareseToken(token, UserDto.class);
        apply.setUserId(userDto.getId());
        if (!redisTemplate.opsForValue().setIfAbsent(JSONUtil.toJsonStr(apply), null, 5, TimeUnit.SECONDS)) {
            return ResultJson.fail(203,"表单不能重复提交",null);
        }
        apply.setCreated(new Date());
        apply.setUserId(userDto.getId());
        applyService.saveOrUpdate(apply);

        return ResultJson.success("编辑成功");
    }

    @GetMapping("getFlowImgByInstanceId")
    public void getFlowImgByInstanceId(String processInstanceId, HttpServletResponse response) throws IOException  {
        //设置页面不缓存
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setHeader("Content-Disposition", "attachment; filename=FlowImg.xml");
        ServletOutputStream outputStream = response.getOutputStream();

        //设置输出的内容的类型为JPEG图像
//        response.setContentType("image/svg");
        response.setContentType("image/svg");

        //写给浏览器
        activitiService.getFlowImgByInstanceId(processInstanceId,outputStream);

        outputStream.flush();
    }


}
